package cn.acac.yygh.hosp.controller.api;

import cn.acac.yygh.exception.MyException;
import cn.acac.yygh.hosp.result.Result;
import cn.acac.yygh.hosp.service.HospitalService;
import cn.acac.yygh.hosp.utils.HttpRequestHelper;
import cn.acac.yygh.model.hosp.Hospital;
import cn.acac.yygh.result.R;
import cn.acac.yygh.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/hosp")
@Api("对接第三方医院的接口")
public class ApiHospitalController {

    // 注入业务层
    @Autowired
    private HospitalService hospitalService;

    @PostMapping("/hospital/show")
    public Result<Hospital> show(HttpServletRequest request){
        // 获取第三方医院的信息
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> map = HttpRequestHelper.switchMap(parameterMap);
        // 根据第三方医院的code进行查询
        String hoscode = (String) map.get("hoscode");   // 医院编号
        String sign = (String) map.get("sign");
        Hospital hospital = hospitalService.findHospitalByHoscode(hoscode,sign);
        return Result.ok(hospital);
    }

    /**
     * 接收第三方医院传递的数据
     * @return
     */
    @ApiOperation("接受第三方医院传递的数据")
    @PostMapping("/saveHospital")
    public R saveHospital(HttpServletRequest request){
        // 获取第三方医院传递的信息
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,Object> map = HttpRequestHelper.switchMap(parameterMap);
        // 判断第三方医院的key是否正确
        String sign = (String) map.get("sign");
        // 根据医院的编码查询数据库
        String key = hospitalService.findSignByHoscode(map.get("hoscode"));
        // 验证信息
        if(!StringUtils.isEmpty(sign) && !StringUtils.isEmpty(key) && sign.equals(MD5.encrypt(key))){
            // 调用servlet层存储第三方医院信息
            // 存储信息之前将医院的logo进行配置
            String logoData = (String) map.get("logoData");
            map.put("logoData",logoData.replace(" ", "+"));
            hospitalService.saveHospital(map);
            return R.ok().code(200);    // 返回成功状态码必须为200
        }else {
            throw new MyException(50000,"效验失败！");
        }
    }
}
